from PIL import Image
import os


def create_image_with_size(target_size, width=800, height=600, initial_quality=85):
    """
    创建一个指定文件大小的JPEG图片。

    :param target_size: 目标文件大小，单位字节
    :param width: 图片宽度
    :param height: 图片高度
    :param initial_quality: 初始JPEG质量
    :return: None
    """
    img = Image.new('RGB', (width, height), color=(255, 255, 255))

    quality = initial_quality
    filename = 'custom_image.jpg'

    while True:
        img.save(filename, 'JPEG', quality=quality)

        # 获取文件大小
        file_size = os.path.getsize(filename)

        if file_size <= target_size:
            print(f"文件已达到目标大小或更小: {file_size} bytes (质量: {quality}%)")
            break
        else:
            print(f"文件大小: {file_size} bytes, 目标大小: {target_size} bytes, 质量: {quality}%")

            # 降低质量
            quality -= 5
            if quality <= 0:
                print("无法达到目标大小，质量已降至0%")
                break


if __name__ == "__main__":
    target_size = 1000 * 1024  # 100 KB
    width = 8000
    height = 8000
    initial_quality = 100

    create_image_with_size(target_size, width, height, initial_quality)